import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.aliyun.odps.udf.UDF;
import com.aliyun.odps.utils.StringUtils;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class SpliderEWGGoods extends UDF {

    private static final String ewg_url = "https://www.ewg.org/";

    private static final String Low = "LOW";
    private static final String Medium_Low ="LOW_MODERATE";
    private static final String Medium_High ="MODERATE";
    private static final String High ="HIGH";

    private static final String Verified_href ="https://phorcys-static.ewg.org/skindeep_rails/score-verified-aac8fea9b2dfca2fe41036b016c3dc97d955ebca605a509f8272fc7d0e275e0f.svg";

    /*public static void main(String[] args) throws Exception{
        HttpClientAPI HttpClientAPI = new HttpClientAPI();
        HttpResult doGet = HttpClientAPI.doGet("https://www.ewg.org/skindeep/products/255631-Verdure_Overnight_Repair_Serum/");
        String body = doGet.getBody();
        evaluate(body);
    }*/

    // 解析EWG商品详情页面所需产品信息

    /**
     * 解析获取 商品名称
     *
     * @param str
     * @return
     */
    public String evaluate(String str) {
        try {
            JSONObject returnObj = new JSONObject();
            Document doc = Jsoup.parse(str);
            // 获取商品对应属性
            Element idProductElement = doc.getElementById("product");
            if (null != idProductElement) {
                // 获取产品名称
                Elements nameElements = idProductElement.getElementsByClass("product-name text-block");
                if (null != nameElements && nameElements.size() == 1) {
                    String name = nameElements.get(0).text();
                    if (StringUtils.isNotBlank(name)) {
                        returnObj.put("name", name);
                    }
                }
                //获取品牌   分类
                Elements brandElements = idProductElement.getElementsByClass("browse-more");
                if(null != brandElements && brandElements.size() == 1){
                    Elements mb40 = brandElements.get(0).getElementsByClass("mb40");
                    if(null != mb40 && mb40.size() == 1){
                        //获取品牌和分类 （如果li的size大于1 第一条就是品牌，剩余为分类，如果size等于1 第一条就是分类）
                        Elements brandLi = mb40.get(0).getElementsByTag("li");
                        if (null != brandLi && brandLi.size() == 1){
                            Element brandEle = brandLi.get(0);
                            String category = brandEle.text();
                            returnObj.put("category", category);

                        }else if(null != brandLi && brandLi.size() > 1){
                            Element brandEle = brandLi.get(0);
                            String brand = brandEle.text();
                            String barnsUrl = ewg_url + brandEle.attr("href");
                            returnObj.put("brand", brand);
                            returnObj.put("barnsUrl", barnsUrl);

                            StringBuffer categorySb = new StringBuffer();
                            for(int i = 1; i< brandLi.size() ; i++){
                                String text = brandLi.get(i).text();
                                categorySb = categorySb.append(text).append("->");
                            }
                            returnObj.put("category", categorySb.substring(0,categorySb.lastIndexOf("->")));

                        }
                    }
                }

                // 获取产品图片
                Elements classElements = idProductElement.getElementsByClass("product-image");
                if (null != classElements && classElements.size() == 1) {
                    Elements imgElements = classElements.get(0).getElementsByTag("img");
                    if (null != imgElements && imgElements.size() == 1) {
                        if (StringUtils.isNotBlank(imgElements.get(0).attr("src"))) {
                            returnObj.put("image", imgElements.get(0).attr("src"));
                        }
                    }
                }
				// 获取产品得分
                Elements scoreElements = idProductElement.getElementsByClass("product-score");
                if (null != scoreElements && scoreElements.size() == 1) {
                    Elements imgElements = scoreElements.get(0).getElementsByTag("img");
                    if (null != imgElements && imgElements.size() == 1) {
                        String productScoreHref = imgElements.get(0).attr("src");
                        if (StringUtils.isNotBlank(productScoreHref) &&
                                !StringUtils.equals(productScoreHref, Verified_href)) {
							//得分图标，截取分数
							//https://phorcys-static.ewg.org/skindeep_rails/score-04-bb0e9bfd7f59473279df3f14964309bbfe042d0d0e848b306a70c2bc6a6b81d8.svg
							//https://phorcys-static.ewg.org/skindeep_rails/score-02-d52d6a7bd5c631c063a8f9a8b9af7f467a14fbf7178dec4fea22618ec5c800b7.svg
							//score-02
							String scoreProduct = productScoreHref.substring(productScoreHref.lastIndexOf("/") + 1, productScoreHref.lastIndexOf("-"));
							String[] split = scoreProduct.split("-");
							if(null != split && split.length == 2){
								returnObj.put("productScore",split[1]);
							}

                        }else if (StringUtils.equals(productScoreHref, Verified_href)){
                            //部分商品是认证商标 分数置位100
                            returnObj.put("productScore",100);
                        }
                    }
                }
                //获取 产品成分,成分得分,成分关心
                StringBuffer ingredientNamesb = new StringBuffer();
                StringBuffer ingredientHrefsb = new StringBuffer();
                Elements ingredientElements = doc.getElementsByClass("table-ingredient-concerns");
                if(null != ingredientElements && ingredientElements.size() ==1){
                    Elements ingredientTbody = ingredientElements.get(0).getElementsByTag("tbody");
                    if(null != ingredientTbody && ingredientTbody.size() == 1){
                        Elements trEles = ingredientTbody.get(0).getElementsByTag("tr");
                        if(null != trEles && trEles.size() > 0){
                            for (Element trEle :trEles){
                                //获取成分
                                String ingredient = null;
                                Elements tdIngredient = trEle.getElementsByClass("td-ingredient");
                                if(null != tdIngredient && tdIngredient.size() == 1){
                                    //获取成分别名
                                    String ingredientAlias = tdIngredient.get(0).getElementsByTag("span").text();
                                    if(StringUtils.isNotBlank(ingredientAlias)){
                                        ingredientAlias = ingredientAlias.replace("Appeared as:","");
                                    }
                                    //成分标准名称
                                    ingredient = tdIngredient.get(0).getElementsByTag("a").text();
                                    String ingredientAppend = ingredient+"$$"+ingredientAlias;
                                    if(StringUtils.isNotBlank(ingredient)){
                                        ingredientNamesb = ingredientNamesb.append(ingredientAppend).append("@@");
                                    }
                                    //获取成分详情页链接
                                    String href = tdIngredient.get(0).getElementsByTag("a").attr("href");
                                    ingredientHrefsb = ingredientHrefsb.append("https://www.ewg.org"+href).append("@@");
                                }
                                //获取成分关心字段
                                String care = null;
                                Elements careIngredient = trEle.getElementsByClass("td-concern");
                                if(null != careIngredient && careIngredient.size() == 1){
                                    care = careIngredient.get(0).text();

                                }
                                //获取成分得分
                                Elements tdScore = trEle.getElementsByClass("td-score");
                                if(null != tdScore && tdScore.size() == 1){
                                    String srcAttr = tdScore.get(0).getElementsByTag("img").get(0).attr("src");
                                    String scoreProduct = srcAttr.substring(srcAttr.lastIndexOf("/") + 1, srcAttr.lastIndexOf("-"));
                                    String[] split = scoreProduct.split("-");
                                    if(null != split && split.length == 2){
                                        if(StringUtils.isNotBlank(ingredient)){
                                            String score = split[1];
                                            score = score+"@@"+care;
                                            //成分安全分
                                            returnObj.put(ingredient,score);
                                        }
                                    }
                                }
                            }
                            String ingredient = ingredientNamesb.substring(0, ingredientNamesb.lastIndexOf("@@"));
                            //将成分格式变成json格式
                            List<Map<String,String >> inredientList = new ArrayList<>();
                            Map<String,String > ingreMap = new HashMap<>();
                            ingreMap.put("goods_name","");
                            ingreMap.put("goods_ingredient",ingredient);
                            inredientList.add(ingreMap);
                            //成分拼接
                            returnObj.put("ingredient",inredientList);
                            returnObj.put("ingredientUrl",ingredientHrefsb.substring(0,ingredientHrefsb.lastIndexOf("@@")));
                        }
                    }
                }

                //获取成分问题
                Elements ingQuesEles = doc.getElementsByClass("gauges grid");
                if (null != ingQuesEles && ingQuesEles.size() == 1){
                    Elements picEles = ingQuesEles.get(0).getElementsByClass("thebigimage");
                    if(null != picEles && picEles.size() > 0){
                        for (Element e : picEles){
                            //获取title
                            String text = e.getElementsByClass("gauge-header-wrapper").text();
                            //获取风险值
                            String value = e.getElementsByClass("gauge-img-wrapper").get(0)
                                    .getElementsByTag("img").attr("alt");
                            String riskValue = "";
                            if (value.contains(Medium_Low)){
                                riskValue = Medium_Low;
                            }else if (value.contains(Low)){
                                riskValue = Low;
                            }else if (value.contains(Medium_High)){
                                riskValue = Medium_High;
                            }else if (value.contains(High)){
                                riskValue = High;
                            }
                            returnObj.put(text,riskValue);
                        }
                    }
                }

                //获取其他成分问题
                Element otherQuesEle = doc.getElementById("other-concerns");
                if(null != otherQuesEle){
                    String otherQuestion = otherQuesEle.text();
                    returnObj.put("otherQuestion",otherQuestion);
                }
                //获取包装信息
                Element packingInfo = doc.getElementById("label-information");
                if(null != packingInfo ){
                    Elements h3Eles = packingInfo.getElementsByTag("h3");
                    Elements pEles = packingInfo.getElementsByTag("p");
                    if((null != h3Eles) && (null != pEles) && (h3Eles.size() == pEles.size())){
                        for(int i = 0;i< h3Eles.size() ;i++){
                            returnObj.put(h3Eles.get(i).text(),pEles.get(i).text());
                        }
                    }

                }
            }

            System.out.println(JSON.toJSONString(returnObj));
            return JSON.toJSONString(returnObj);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

}
